package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import util.HttpRequestUtils;

/**
 * Servlet implementation class CallBackServlet
 */
@WebServlet("/callBackLogin")
public class CallBackServlet extends HttpServlet {
	 
	private static final String Appid = "wx9c8b33b59d002f38"; //科泰学堂  固定的
    private static final String Secret = "79a95a7c92f76128c57a6e5756dd1057"; //固定的

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		PrintWriter out = response.getWriter();
		
		// 获取发生第一次请求后,微信给的回应,如果用户拒绝登陆code参数不会返回
        String code = request.getParameter("code");

        // 第二次发送请求,并根据返回的json数据,解析获取access_token
        //不用改
        StringBuffer sb = new StringBuffer(
                "https://api.weixin.qq.com/sns/oauth2/access_token?")// 通过code换取access_token
                .append("appid=").append(Appid)// 跟第一次请求的一致
                .append("&secret=").append(Secret)// 查看科泰服务器信息_微信开发对应appid的
                .append("&code=").append(code)// 第一次请求后得到的参数
                .append("&grant_type=authorization_code");
        //发送请求
        String msg_token = HttpRequestUtils.sendGetRequest(sb.toString());
        
        //成功可以得到openId ,失败得到{"errcode":40029,"errmsg":"invalid code"}
        System.out.println("请求成功信息: ----------------"+msg_token);
        out.print("msg: "+msg_token );
        
        //获取access_token凭证 及openid,用于获取用户信息
        JSONObject jsonObject = JSONObject.parseObject(msg_token.toString());
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        
        // 发送第三次请求:若是要获取用户信息,使用/sns/userinfo 获取用户个人信息
        //复制粘贴即可
        sb = new StringBuffer("https://api.weixin.qq.com/sns/userinfo?")
                .append("access_token=").append(access_token)
                .append("&openid=").append(openid);
        
        String msg_userInfo = HttpRequestUtils.sendGetRequest(sb.toString());
        
        JSONObject userInfo =jsonObject.parseObject(msg_userInfo.toString());
        String sex = userInfo.getString("sex");   // 获取用户的性别
        String province = userInfo.getString("province");   // 获取用户的省
        String city = userInfo.getString("city");  // 市
        String headimgurl = userInfo.getString("headimgurl"); // 用户的头像
        String unionid = userInfo.getString("unionid"); // 用户的唯一标示
        String nickname = userInfo.getString("nickname"); // 昵称
        //nickname=new String(nickname.getBytes("ISO-8859-1"), "UTF-8");//中文乱码
        String country = userInfo.getString("country"); // 国家，如中国为CN
       
        // 在前台显示
        StringBuffer msg =new StringBuffer();
        msg.append("\n 性别: "+ sex);
        msg.append("\n 国籍: "+ country);
        msg.append("\n 省份: "+ province);
        msg.append("\n 城市: "+city);
        msg.append("\n 头像地址: "+headimgurl);
        msg.append("\n unionid: "+unionid);
        msg.append("\n 昵称: "+nickname);
        
        System.out.println("\n=================================");
        System.out.println("userinfo: "+ msg);
        out.print("userInfo  " + msg);
        out.flush();
        out.close();
	
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
